<template>
  <el-dialog
      title="短信验证码"
      v-model="visible"
      width="30%"
      :close-on-click-modal="false"
      @closed="closeDialog"
  >
    <el-form ref="form" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="短信验证码" prop="captcha">
        <el-input v-model="formData.captcha" placeholder="请输入6位短信验证码"/>
      </el-form-item>

      <el-form-item label="验证码操作">
        <el-button
            type="primary"
            @click="sendCaptcha"
            :disabled="isCounting" style="width: 100%"
        >
          {{ isCounting ? `${countdown} 秒后重发` : "发送验证码" }}
        </el-button>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>

import {smsSendCaptchaByUserIdApi} from "@/api/setup/sms";

const smsTplCode = process.env.VUE_APP_SMS_TPL_CODE;

export default {
  data() {
    let checkCaptcha = (rule, value, callback) => {
      const reg = /^\d{6}$/;
      if (!value) {
        return callback(new Error("短信验证码不能为空"));
      } else if (!reg.test(value)) {
        callback(new Error("验证码必须为6位数字"));
      } else {
        callback();
      }
    };

    return {
      visible: false,
      resolveCallback: null,
      formData: {
        captcha: ''
      },
      rules: {
        captcha: [
          {required: true, validator: checkCaptcha, trigger: "blur"}
        ]
      },
      isCounting: false,
      countdown: 60,
      timer: null,
    };
  },
  methods: {
    /**
     * 显示弹窗
     */
    show(callback) {
      this.visible = true;
      this.resolveCallback = callback;
    },

    /**
     * 发送验证码
     */
    sendCaptcha() {
      smsSendCaptchaByUserIdApi({
        tplCode: smsTplCode,
      })

      this.isCounting = true;
      this.countdown = 60;

      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          this.isCounting = false;
          clearInterval(this.timer);
        }
      }, 1000);
    },

    /**
     * 表单提交
     */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const captcha = this.formData.captcha;
          if (this.resolveCallback) {
            this.resolveCallback(captcha);
          }
        } else {
          return false;
        }
      });
    },

    /**
     * 手动关闭弹窗
     */
    closeDialog() {
      this.visible = false;
      this.$refs.form.resetFields();
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
